import dayjs from "dayjs";
import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import elForm from '../form.vue'

import { stationList, addStation, updateStation, delStation, GetAllStation } from '@/utils/api/dispatch/station'
import { GetAllMap } from '@/utils/api/dispatch/map'

export function useDept() {
  const form = reactive({
    stationname: "",
    x: "",
    y: "",
    stationtype: "",
    status: null,
    pageNumber: 0,
    pageSize: 10,
    sortName: "createtime",
    sortType: 0
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle, statusStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  // 所属地图select
  var mapTypes = ref([])
  // 站点select
  var stationSelect = ref([])
  // 类型select
  const stationTypes = [
    { value: 0, label: '路径点' },
    { value: 1, label: '返航点' },
    { value: 2, label: '充电点' },
    { value: 3, label: '货位点' },
    { value: 4, label: '电梯点' },
  ]

  // 类型
  function formatType(status) {
    const stateMap = {
      0: '路径点',
      1: '返航点',
      2: '充电点',
      3: '货位点',
      4: '电梯点'
    }
    return stateMap[status]
  }

  // 状态
  function formatStatus(status) {
    const stateMap = {
      0: '禁用',
      1: '启用',
      2: '锁定',
    }
    return stateMap[status]
  }

  const columns: TableColumnList = [
    {
      label: "站点名称",
      prop: "name",
      width: 150,
      align: "left",
      sortable: true
    },
    {
      label: "X轴",
      prop: "x",
      width: 100,
      align: "left",
      sortable: true
    },
    {
      label: "Y轴",
      prop: "y",
      width: 100,
      align: "left",
      sortable: true
    },
    {
      label: "角度",
      prop: "angle",
      width: 100,
      align: "left",
      sortable: true
    },
    {
      label: "所属地图",
      prop: "mapid",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <span>{mapTypes.value.find(v => { return v.id === row.mapid })?.name}</span >
      )
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={statusStyle.value(row.status)}>
          {formatStatus(row.status)}
        </el-tag>
      )
    },
    {
      label: "类型",
      prop: "type",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.type)}>
          {formatType(row.type)}
        </el-tag>
      )
    },
    {
      label: "关联总图站点",
      prop: "parentid",
      minWidth: 150,
      cellRenderer: ({ row, props }) => (
        <span>{stationSelect.value.find(v => { return v.stationid === row.parentid })?.stationname}</span >
      )
    },
    {
      label: "备注",
      prop: "note",
      minWidth: 200,
      align: "left"
    },
    {
      label: "操作",
      headerAlign:"center",
      fixed: "right",
      align: "right",
      width: 200,
      slot: "operation"
    }
  ]

  async function onSearch() {
    loading.value = true;
    //@ts-ignore
    const { Content } = await stationList(form);
    let newData = Content.Results;
    dataList.value = newData;
    pagination.total = Content.TotalCount;
    pagination.pageSize = Content.PageSize;
    pagination.currentPage = Content.PageNumber + 1;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  // 重置
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}站点`,
      props: {
        formInline: {
          name: row?.name ?? "",
          type: row?.type ?? null,
          x: row?.x ?? null,
          y: row?.y ?? null,
          sort: row?.sort ?? null,
          status: row?.status ?? 1,
          note: row?.note ?? "",
          mapid: row?.mapid ?? null,
          parentid: row?.parentid ?? undefined,
        },
        stationTypes: stationTypes || [],
        mapTypes: mapTypes || [],
        stationSelect: stationSelect || []
      },
      width: "35%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(elForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了站点名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            // console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              addStation(curData).then(res => {
                if (res.Code === 0) chores();
              })
            } else {
              let data = Object.assign(curData, { id: row.id })
              updateStation(data).then(res => {
                if (res.Code === 0) chores();
              })
            }
          }
        });
      }
    })
  }

  // 删除
  function handleDelete(row) {
    ElMessageBox.confirm(
      `是否确认删除站点名称为${row.name}的数据项?`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
    ).then(() => {
      delStation(row.id).then(res => {
        if (res.Code === 0) {
          message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
          onSearch();
        }
      })
    }).catch(() => { })
  }

  function handleSizeChange(val: number) {
    form.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    form.pageNumber = val - 1
    onSearch()
  }

  onMounted(async () => {
    // 地图select
    let { Content: map } = await GetAllMap()
    let allMap = map.filter(v => { return v.type === 0 })
    mapTypes.value = map
    // 站点select
    let { Content: stations } = await GetAllStation({ status: 1, mapid: allMap[0].id })
    stationSelect.value = stations
    onSearch()
  })

  return {
    columns,
    loading,
    dataList,
    openDialog,
    handleDelete,
    form,
    onSearch,
    resetForm,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    stationTypes
  }
}